﻿using MyHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using System.Windows.Threading;
using clf.weighing.entity;
using CheckBox = System.Windows.Controls.CheckBox;
using Button = System.Windows.Controls.Button;


namespace weighing
{
    /// <summary>
    /// OutputDataContent.xaml 出库数据 的交互逻辑
    /// </summary>
    public partial class OutputDataContent : WeighingDataUserContent
    {

        public OutputDataContent()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            this.Data_Grid.ItemsSource = mWeihingBillVos;
            currBillType = WeightingBillType.Sale;
            this.Loaded += OutputDataContent_Loaded;
            this.IsVisibleChanged += OutputDataContent_IsVisibleChanged;
            this.Unloaded += OutputDataContent_Unloaded;    
            DelegeteFactory.Instance.OnBackupBillFieldChanged += OnBackupBillFieldChangedHandle;
        }

        #region load and timer
        private void OutputDataContent_Loaded(object sender, RoutedEventArgs e)
        {
            CreateBackupFieldUi(this.Data_Grid);

            ShowOrHideColumns();

            LoadData();

            InitTimer();

        }

        private void OutputDataContent_Unloaded(object sender, RoutedEventArgs e)
        {
            DisposeTime();

            DelegeteFactory.Instance.OnBackupBillFieldChanged += OnBackupBillFieldChangedHandle;
        }

        private void OutputDataContent_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.IsLoaded == false) return;
            if (this.IsVisible)
            {
                mTimer?.Start();

                LoadData();
            }
            else
            {
                mTimer?.Stop();
            }
        }
        public void OutputDataUC_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //this.Data_Grid.Height = this.dataRow.ActualHeight;
        }
        private void InitTimer()
        {
            mTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(App.Config.SystemConfig.DataRefreshInterval),               
            };
            mTimer.Tick += (obj, eventArgs) =>
            {
                this.Dispatcher.Invoke(() => { LoadData(); });
            };
        }
        private void DisposeTime()
        {
            if (mTimer != null)
            {              
                mTimer.Stop();
            }
        }
        #endregion

        #region data grid event

        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ChangeDataColor(e);
        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.Data_Grid.SelectedItem is WeighingBillVo vo)
            {
                mWeighingBillVo = vo;

                if (mWeighingBillVo.Status == 1)
                {
                    OpenDetail();
                }
                else
                {
                    string msg = $"是否要对 {mWeighingBillVo.CarNumber} 进行 出场过磅，\r\n 请认真核对车牌号,减少出错？";
                    var result = CommonFunction.Ask(msg);
                    if (result ==  MessageBoxResult.Yes)
                    {
                        if (App.Current.MainWindow is MainWindow mw)
                        {
                            if (mw.WeighingUIBorder.Child is NomalWeighingUc nouc)
                            {
                                nouc.OutWeighingRb.IsChecked = true;
                                nouc.outputWeighingUc.IsRecongnizePlateWeighing = true;
                                nouc.outputWeighingUc.outFactoryRb.IsChecked = true;
                                nouc.outputWeighingUc.IsInsert = false;
                                nouc.outputWeighingUc.OnCarSelected(vo.mWeighingBill);
                                nouc.InputWeighingUc.ShowOrHidePricePanel();
                                nouc.outputWeighingUc.IsRecongnizePlateWeighing = false;
                            }
                            else
                            {
                                Growl.Info("不能操作", "main");
                            }
                        }
                        else
                        {
                            Growl.Info("不能操作", "main");
                        }
                    }
                }
            }
            else
            {
                mWeighingBillVo = null;
            }
        }

        private void DataGrid_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
                if (this.Data_Grid.SelectedItem is WeighingBillVo bill)
                {
                    if (bill.Status == 0 && (App.CurrentUser?.roleType == (int)UserRoleType.WeighingManager || App.CurrentUser.roleType == (int)UserRoleType.Developer))
                    {
                        DeleteBill(bill.mWeighingBill);
                    }
                }
        }
        #endregion

        //防止重复加载数据
        private bool IsDataLoading = false;

        public void LoadData()
        {
            if (IsDataLoading || this.IsVisible == false) return;
            IsDataLoading = true;
            mWeihingBillVos.Clear();
            var list = WeighingBillDao.Instance.GetTodayBills(currBillType);
            list?.ForEach((i) => { mWeihingBillVos.Add(new WeighingBillVo(i)); });
            this.allCb.IsChecked = true;
            IsDataLoading = false;
        }

        #region data Filler

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded)
            {
                if (sender is CheckBox checkBox)
                {
                    if (checkBox.Name == "allCb")
                    {
                        this.noOutCb.IsChecked = false;
                        this.outCb.IsChecked = false;
                        this.upOneCb.IsChecked = false;
                        this.upTwoCb.IsChecked = false;
                        this.noPrintCb.IsChecked = false;
                    }
                    else
                    {
                        this.allCb.IsChecked = false;
                    }
                }
                FilerData();
            }
        }


        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (this.allCb.IsChecked == false) FilerData();
        }
        /// <summary>
        /// 过虑 已经已经显示的数据
        /// </summary>
        private List<WeighingBillVo> tempBillVos = new List<WeighingBillVo>();
        private void FilerData()
        {
            if(IsDataLoading) return;
            if (this.allCb.IsChecked == true)
            {
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mWeihingBillVos;
            }
            else
            {
                tempBillVos.Clear();
                foreach (var item in mWeihingBillVos)
                {

                    if (this.noOutCb.IsChecked == true)
                    {
                        if (item.Status == 0)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.outCb.IsChecked == true)
                    {
                        if (item.Status == 1)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.upOneCb.IsChecked == true)
                    {
                        if (item.UpGovernmentStatus == 1)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.upTwoCb.IsChecked == true)
                    {
                        if (item.UpGovernmentStatus == 2)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.noPrintCb.IsChecked == true)
                    {
                        if (item.PrintTimes == 0)
                        {
                            tempBillVos.Add(item);
                        }
                    }
                }
                if (tempBillVos.Count > 0)
                {
                    this.Data_Grid.ItemsSource = null;
                    this.Data_Grid.ItemsSource = tempBillVos;
                }
                else
                {
                    Growl.Info("没有匹配的数据，显示所有数据");
                    this.allCb.IsChecked = true;
                }
            }
        }
        #endregion

        #region 动态显示列

        private Dictionary<Int32, CheckBox> columnsDics;
        private void ColumnsSettingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (columnsDics == null)
            {
                columnsDics = new Dictionary<int, CheckBox>();
                var cols = this.Data_Grid.Columns;
                var style = FindResource("CheckBoxBaseStyle") as Style;
                for (int i = 0; i < cols.Count; i++)
                {
                    var col = cols[i];
                    var cb = new CheckBox()
                    {
                        Style = style,
                        Content = col.Header,
                        HorizontalAlignment =System.Windows. HorizontalAlignment.Left,
                        Tag = i,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    if (col.Visibility == Visibility)
                    {
                        cb.IsChecked = true;
                    }
                    else
                    {
                        cb.IsChecked = false;
                    }
                    cb.Checked += SearchLiset_Checked;
                    cb.Unchecked += SearchLiset_Unchecked;
                    columnsDics.Add(i, cb);
                }
                foreach (var item in columnsDics)
                {
                    this.columnsPanel.Children.Add(item.Value);
                }
            }
            this.columnPopup.IsOpen = !columnPopup.IsOpen;
        }
        private void SearchLiset_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox cb)
            {
                var index = (int)cb.Tag;
                var col = this.Data_Grid.Columns[index];
                if (col != null)
                {
                    col.Visibility = Visibility.Visible;

                    string header = cb.Content.ToString();

                    SaveColumnSetting(header, true);
                }
            }
        }

        private void SearchLiset_Unchecked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox cb)
            {
                var index = (int)cb.Tag;
                var col = this.Data_Grid.Columns[index];
                if (col != null)
                {
                    col.Visibility = Visibility.Collapsed;

                    string header = cb.Content.ToString();
                    SaveColumnSetting(header, false);
                }
            }
        }
        #endregion
        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button btn)
            {
                if (btn.Tag is WeighingBillVo bill)
                {
                    mWeighingBillVo = bill;
                    OpenDetail();
                }
                else { mWeighingBillVo = null; }
            }
        }

        private void OpenDetail()
        {
            this.DrawerHeaderTb.Text = mWeighingBillVo.Number + " 磅单详情";
            this.detailRootBorder.Content = null;
            StackPanel panel = new StackPanel();
            var detail = new OutPrint() { DataContext = mWeighingBillVo };
            panel.Children.Add(detail);
            var img = new BillImageUC(mWeighingBillVo.mWeighingBill);
            panel.Children.Add(img);
            this.detailRootBorder.Content = panel;
            this.DrawerBottom.IsOpen = true;
        }


        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                    var type = bill.Status == (int)BillStatus.Finished
                        ? WeightingBillType.WeighintBill
                        : WeightingBillType.LoadingBill;

                    if (App.Config.BillPrintConfig.IsUserExclCustomBill)
                    {
                        new PrintEXCLWindow(bill.Id)
                        {
                            Owner = App.Current.MainWindow
                        }.ShowDialog();
                    }
                    else
                    {
                        new PrintWindow(bill.Id, type)
                        {
                            Owner = App.Current.MainWindow
                        }.ShowDialog();
                    }
                }
            }
        }

        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                    DeleteBill(bill.mWeighingBill);
                }
            }
        }

        private void DeleteBill(WeighingBill bill)
        {
            string msg = $"是否要删除编号为 {bill.number} 的过磅数据？";
            var result = CommonFunction.Ask(msg);
            if (result == MessageBoxResult.Yes)
            {
                this.DeleteReasonPopup.Tag = bill.number; //将 编号 进行传递
                this.DeleteReasonPopup.IsOpen = true;
            }
        }

        #region popup delete reason  弹窗删除
        private void PopupCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.DeleteReasonPopup.IsOpen = false;
        }

        private void PopupDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            string reason = this.DeleteReasonCb.Text.Trim();
            if (reason.Length < 5)
            {
               CommonFunction.AlertInfo("请选择或者输入删除该数据的原因，5个字以上");
                return;
            }
            this.DeleteReasonPopup.IsOpen = false;
            string number = this.DeleteReasonPopup.Tag.ToString();
            if (string.IsNullOrEmpty(number))
            {
                Growl.Info("删除失败！", "main");
                return;
            }
            bool res = WeighingBillDao.Instance.SoftDelete(number, reason);
            if (res)
            {
                LoadData();
                Growl.Success($"{number} 删除成功", "main");

                Log.Info($"{number} 被 {App.CurrentUser?.name} 删除成功");
            }
            else
            {
                Growl.Error($"{number} 删除失败", "main");
            }
        }
        private void DeleteReasonPopup_Closed(object sender, EventArgs e)
        {
            this.DeleteReasonCb.SelectedIndex = -1;
            this.DeleteReasonCb.Text = "";
        }


        #endregion

        //取消出场操作
        private void RepetitionOutBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                    var info = $"是否要取消编号为 {bill.Number} 的过磅数据出场操作？此操作需要谨慎";
                    var result = CommonFunction.Ask(info);
                    if (result == MessageBoxResult.Yes)
                    {
                        string msg = "操作成功！只改变数据的状态，未改变数据原来过磅的值，再次出场时会覆盖原来的值";

                        int res = WeighingBillDao.Instance.ChangeStatus(bill.Number, BillStatus.NoOut);
                        if (res > 0)
                        {
                            Growl.Success(msg);
                            LoadData();
                     
                            Log.Info($"用户：{App.CurrentUser?.name} 在 {DateTimeHelper.getCurrentDateTime()} 将磅单编号为 {bill.Number} 取消出场");                            
                           
                        }
                        else
                        {
                            msg = "操作失败！";
                            Growl.Success(msg);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 过虑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBar_OnSearchStarted(object sender, HandyControl.Data.FunctionEventArgs<string> e)
        {
            string key = this.searcher.Text.Trim();
            Console.WriteLine("--" + key);
            List<WeighingBillVo> temp = new List<WeighingBillVo>();
            if(!string.IsNullOrEmpty(key))
            {
                foreach (WeighingBillVo vo in mWeihingBillVos)
                {
                    if ((vo.CarNumber ?? "").Contains(key)
                        || (vo.MaterialName ?? "").Contains(key)
                        || (vo.SendCompanyName ?? "").Contains(key)
                        || (vo.ReceiveCompanyName ?? "").Contains(key))
                    {
                        temp.Add(vo);
                    }
                }
                if (temp.Count > 0)
                {
                    this.Data_Grid.ItemsSource = temp;
                }
                else {
                   Growl.Info("没有过虑到任何数据，请换个关键字", "main");
                }
            }
            else
            {
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mWeihingBillVos;
            }
        }

        private void Searcher_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.searcher.Text)) {
                this.Data_Grid.ItemsSource = null;
                this.Data_Grid.ItemsSource = mWeihingBillVos;
            }
        }
        // to edit
        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            if (btn?.Tag is WeighingBillVo vo)
            {
                new BillEditWindow(vo)
                {
                    Owner = App.Current.MainWindow,
                    OnChanged = (res) => { if (res) LoadData(); }
                }.ShowDialog();
            }
        }


        private void OnBackupBillFieldChangedHandle(BackupBillField field)
        {
            if (field != null || field.billType == (int)WeightingBillType.Sale)
            {
                UpdateBackupColumns(field);
            }
        }

        public override DataGrid GetDataGrid()
        {
            return this.Data_Grid;
        }
    }
}
